package com.seres.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;

/**
 * @Description : redis配置
 * @ClassName : JedisClusterConfig
 * @Author : 程磊
 * @Date: 2020-06-22 16:26
 */
@Configuration
@Slf4j
public class JedisClusterConfig {

    //redis集群地址，用‘,’分割
    @Value("${spring.redis.clusterNodes}")
    private String clusterNodes;
    //连接时间
    @Value("${spring.redis.connectionTimeout}")
    private int connectionTimeout;

    //响应超时（毫秒）
    @Value("${spring.redis.soTimeout}")
    private int soTimeout;
    //出现异常最大重试次数
    @Value("${spring.redis.maxAttempts}")
    private int maxAttempts;

    //最大连接数
    @Value("${spring.redis.pool.maxActive}")
    private int maxActive;
    //最大空闲连接数
    @Value("${spring.redis.pool.maxIdle}")
    private int maxIdle;
    //最小空闲连接数
    @Value("${spring.redis.pool.minIdle}")
    private int minIdle;
    //获取连接最大等待时间
    @Value("${spring.redis.pool.maxWait}")
    private int maxWait;


    @Bean
    public JedisPoolConfig getJedisPool(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxActive);
        poolConfig.setMinIdle(minIdle);
        poolConfig.setMaxWaitMillis(maxWait);
        return poolConfig;
    }

    @Bean
    public JedisCluster getJedisCluster(JedisPoolConfig jedisPoolConfig) {
        String[] serverArray = clusterNodes.split(",");//获取服务器数组(这里要相信自己的输入，所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), NumberUtils.toInt(ipPortPair[1].trim())));
        }

        JedisCluster jedisCluster = new JedisCluster(nodes, connectionTimeout, soTimeout, maxAttempts, jedisPoolConfig);
        log.info("jedis启动成功");
        return jedisCluster;
    }
}
